<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	var count = 1;
	
	$(document).ready(function(){
		if(${sessionScope.userid == null}){
			alert("로그인이 필요합니다.");
			location.href="${path}/member/login.jsp";
		}	
	});
	
	function addForm(stpeListSize){
		if(count < stpeListSize){
			<c:forEach var='row' items='${map.step_list}'>
				var addedFormDiv = document.getElementById("addedFormDiv");
		        var str = "";
				
		        str+="<div style='margin-left: 50px; margin-top: 20px;'>STEP "+count+"</div>";
		        str+="<div style='margin-left: 50px;'>";
		        str+="<div id='subPreview"+count+"' style='width: 200px; height: 200px; color: black; border: 2px solid black; background-image: url(${path}/images/step/${row.recipe_idx}/${row.image1}); background-size: contain; background-repeat: no-repeat; background-position: center;'></div><br>";
		        str+="<input type='file' style='width: 350px;' id='subImg_"+count+"' name='subImg_"+count+"' onchange=subPreviewImage(this,'subPreview"+count+"')>";
		        str+="</div>";
		        str+="<div style='margin-left: 50px;'>";
		        str+="<input type='checkbox' id='important_"+count+"' name='important_"+count+"' value='1' <c:if test='${row.important == 1}'>checked</c:if>><b>important</b>"; 
		        str+="</div>";
		        str+="<div style='margin-left: 50px;'>";
		        str+="<b>content</b><br><br>";
		        str+="<textarea id='content_"+count+"' name='content_"+count+"' rows='10' cols='72'>${row.content}</textarea>";
		        str+="</div>";
		        
		        // 추가할 폼(에 들어갈 HTML)
				var addedDiv = document.createElement("div"); // 폼 생성
		
		        addedDiv.id = "added_"+count; // 폼 Div에 ID 부 여 (삭제를 위해)
		        addedDiv.innerHTML  = str; // 폼 Div안에 HTML삽입
		        addedFormDiv.appendChild(addedDiv); // 삽입할 DIV에 생성한 폼 삽입
		
		        count++;
		
		        document.baseForm.count.value=count; // 다음 페이지에 몇 개의 폼을 넘기는지 전달하기 위해 히든 폼에 카운트 저장
			</c:forEach>
		}else{
			if(count > 10){
				alert("STEP은 10개까지 등록하실 수 있습니다.");
			}else{
		    	var addedFormDiv = document.getElementById("addedFormDiv");
		        var str = "";
		
		        str+="<div style='margin-left: 50px; margin-top: 20px;'>STEP "+count+"</div>";
		        str+="<div style='margin-left: 50px;'>";
		        str+="<div id='subPreview"+count+"' style='width: 200px; height: 200px; color: black; border: 2px solid black; background-image: url(${path}/images/icons/recipeNull.png); background-size: 100%;'></div><br>";
		        str+="<input type='file' style='width: 350px;' id='subImg_"+count+"' name='subImg_"+count+"' onchange=subPreviewImage(this,'subPreview"+count+"')>";
		        str+="</div>";
		        str+="<div style='margin-left: 50px;'>";
		        str+="<input type='checkbox' id='important_"+count+"' name='important_"+count+"' value='1'><b>important</b>"; 
		        str+="</div>";
		        str+="<div style='margin-left: 50px;'>";
		        str+="<b>content</b><br><br>";
		        str+="<textarea id='content_"+count+"' name='content_"+count+"' rows='10' cols='72'></textarea>";
		        str+="</div>";
		
		        // 추가할 폼(에 들어갈 HTML)
				var addedDiv = document.createElement("div"); // 폼 생성
		
		        addedDiv.id = "added_"+count; // 폼 Div에 ID 부 여 (삭제를 위해)
		        addedDiv.innerHTML  = str; // 폼 Div안에 HTML삽입
		        addedFormDiv.appendChild(addedDiv); // 삽입할 DIV에 생성한 폼 삽입
		
		        count++;
		
		        document.baseForm.count.value=count; // 다음 페이지에 몇 개의 폼을 넘기는지 전달하기 위해 히든 폼에 카운트 저장
			}
		}
	}

	function delForm(){
		var addedFormDiv = document.getElementById("addedFormDiv");
	    if(count >1){ // 현재 폼이 두개 이상이면	
	    	var addedDiv = document.getElementById("added_"+(--count)); // 마지막으로 생성된 폼의 ID를 통해 Div객체를 가져옴
			addedFormDiv.removeChild(addedDiv); // 폼 삭제  
		}else{ // 마 지막 폼만 남아있다면
			document.baseForm.reset(); // 폼 내용 삭제 
		}
	}

	function moveHome() {
		location.href="${path}/index.jsp";
	}
	
	function moveWrite() {
		if(${sessionScope.userid == null} ){
			location.href="${path}/member/login.jsp";
		}else{
			location.href="${path}/recipe/recipe_write.do";
		}
	}
	
	function previewImage(targetObj, previewId) {
        var preview = document.getElementById(previewId); //div id   
        var ua = window.navigator.userAgent;    	  
        
        if (ua.indexOf("MSIE") > -1) {//ie일때
            targetObj.select();            
            try {
                var src = document.selection.createRange().text; // get file full path 
                $("#img").attr("src",src);
                var ie_preview_error = document
                        .getElementById("ie_preview_error_" + previewId);
                if (ie_preview_error) {
                    preview.removeChild(ie_preview_error); //error가 있으면 delete
                }
                var img = document.getElementById(previewId); //이미지가 뿌려질 곳 

                img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"
                        + src + "', sizingMethod='scale')"; //이미지 로딩, sizingMethod는 div에 맞춰서 사이즈를 자동조절 하는 역할
            } catch (e) {
                if (!document.getElementById("ie_preview_error_" + previewId)) {
                    var info = document.createElement("<p>");
                    info.id = "ie_preview_error_" + previewId;
                    info.innerHTML = "a";
                    preview.insertBefore(info, null);
                }
            }
        } else { //ie가 아닐때
            var files = targetObj.files;
            for ( var i = 0; i < files.length; i++) {

                var file = files[i];

                var imageType = /image.*/; //이미지 파일일경우만.. 뿌려준다.
                if (!file.type.match(imageType))
                    continue;

                var prevImg = document.getElementById("prev_" + previewId); //이전에 미리보기가 있다면 삭제
                if (prevImg) {
                    preview.removeChild(prevImg);
                }

                var img = document.createElement("img"); //크롬은 div에 이미지가 뿌려지지 않는다. 그래서 자식Element를 만든다.
                img.id = "prev_" + previewId;
                img.classList.add("obj");
                img.file = file;
                img.style.width = '350px'; //기본설정된 div의 안에 뿌려지는 효과를 주기 위해서 div크기와 같은 크기를 지정해준다.
                img.style.height = '350px';
                
                preview.appendChild(img);

                if (window.FileReader) { // FireFox, Chrome, Opera 확인.
                    var reader = new FileReader();
                    reader.onloadend = (function(aImg) {
                        return function(e) {
                            aImg.src = e.target.result;
                        };
                    })(img);
                    reader.readAsDataURL(file);
                } else { // safari is not supported FileReader
                    //alert('not supported FileReader');
                    if (!document.getElementById("sfr_preview_error_"+ previewId)) {
                        var info = document.createElement("p");
                        info.id = "sfr_preview_error_" + previewId;
                        info.innerHTML = "not supported FileReader";
                        preview.insertBefore(info, null);
                    }
                }
            }
        } 
    }
	
	function subPreviewImage(targetObj, previewId) {
        var preview = document.getElementById(previewId); //div id   
        var ua = window.navigator.userAgent;    	  
        
        if (ua.indexOf("MSIE") > -1) {//ie일때
            targetObj.select();            
            try {
                var src = document.selection.createRange().text; // get file full path 
                $("#img").attr("src",src);
                var ie_preview_error = document
                        .getElementById("ie_preview_error_" + previewId);
                if (ie_preview_error) {
                    preview.removeChild(ie_preview_error); //error가 있으면 delete
                }
                var img = document.getElementById(previewId); //이미지가 뿌려질 곳 

                img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"
                        + src + "', sizingMethod='scale')"; //이미지 로딩, sizingMethod는 div에 맞춰서 사이즈를 자동조절 하는 역할
            } catch (e) {
                if (!document.getElementById("ie_preview_error_" + previewId)) {
                    var info = document.createElement("<p>");
                    info.id = "ie_preview_error_" + previewId;
                    info.innerHTML = "a";
                    preview.insertBefore(info, null);
                }
            }
        } else { //ie가 아닐때
            var files = targetObj.files;
            for ( var i = 0; i < files.length; i++) {

                var file = files[i];

                var imageType = /image.*/; //이미지 파일일경우만.. 뿌려준다.
                if (!file.type.match(imageType))
                    continue;

                var prevImg = document.getElementById("prev_" + previewId); //이전에 미리보기가 있다면 삭제
                if (prevImg) {
                    preview.removeChild(prevImg);
                }

                var img = document.createElement("img"); //크롬은 div에 이미지가 뿌려지지 않는다. 그래서 자식Element를 만든다.
                img.id = "prev_" + previewId;
                img.classList.add("obj");
                img.file = file;
                img.style.width = '200px'; //기본설정된 div의 안에 뿌려지는 효과를 주기 위해서 div크기와 같은 크기를 지정해준다.
                img.style.height = '200px';
                
                preview.appendChild(img);

                if (window.FileReader) { // FireFox, Chrome, Opera 확인.
                    var reader = new FileReader();
                    reader.onloadend = (function(aImg) {
                        return function(e) {
                            aImg.src = e.target.result;
                        };
                    })(img);
                    reader.readAsDataURL(file);
                } else { // safari is not supported FileReader
                    //alert('not supported FileReader');
                    if (!document.getElementById("sfr_preview_error_"+ previewId)) {
                        var info = document.createElement("p");
                        info.id = "sfr_preview_error_" + previewId;
                        info.innerHTML = "not supported FileReader";
                        preview.insertBefore(info, null);
                    }
                }
            }
        } 
    }
</script>
</head>
<body>
<hr style="height: 5px; background-color: orange;">
<span style="font: 30px bold; margin-left: 30px;">§ Recipe_Edit §</span>
<div style="background-color: orange; display: inline-block; float: right; vertical-align: middle; margin-left: 20px; padding-left: 10px; padding-right: 10px;">
<input type="image" id="btnHome" src="${path}/images/icons/btnHome.png" width="50px" height="50px" onclick="moveHome();">
<input type="image" id="btnWrite" src="${path}/images/icons/btnWrite.png" width="50px" height="50px" onclick="moveWrite();">
</div>
<hr style="height: 5px; background-color: orange;">
<form name="baseForm" action="${path }/recipe/recipe_edit.do?idx=${map.idx}" method="post" enctype="multipart/form-data">
	<input type="hidden" name="count" value="0"><!-- 카운터 Hidden -->
	<div style="margin-top: 20px; margin-bottom: 20px; margin-left: 50px; font-family: fantasy; font: 30px bold; color: orange;">
		Connected to : ${sessionScope.userid }<br><br><input type="hidden" id="userid" name="userid" value="${sessionScope.userid}">
	</div>
	<div style="margin-top: 20px; margin-bottom: 20px; margin-left: 50px;">
		<b>SUBJECT</b><br><br>
		<input type="text" id="subject" name="subject" value="${map.recipe_list.subject }" style="width: 600px; margin-left: 10px;">
	</div>
	<div style="margin-bottom: 20px; margin-left: 50px;">
		<b>HISTORY</b><br><br>
		<textarea id="history" name="history" rows="3" cols="72" style="margin-left: 10px;">${map.recipe_list.history }</textarea>
	</div>
	<div style="margin-bottom: 20px; margin-left: 50px;">
		<b>FINAL_IMAGE</b>
		<div id='final_preview' style='margin-top: 10px; margin-bottom: 10px; margin-left: 60px; margin-right: 10px; width: 350px; height: 350px; color: black; border: 2px solid black; background-image: url("${path}/images/recipe/${map.recipe_list.idx}/${map.recipe_list.image}"); background-repeat: no-repeat; background-size: contain; background-position: center;'></div><br>
		<input style="margin-left: 60px; width: 450px;" type="file" id="final_img" name="final_img" onchange="previewImage(this,'final_preview')">
	</div>
	<table border="5" bordercolor="white" width="650px" style="margin-bottom: 20px; margin-left: 50px; color: white; text-align: center;">
		<tr>
			<td style="">SELECT LIST - TYPE
			<td>SELECT LIST - INGREDIENT
			<td>SELECT LIST - TIME
		<tr>
			<td>
				<select id="type" name="type" size="3" style="width: 150px; min-height: 50px;">
					<c:forEach var="row" items="${map.type }">
					<option value="${row}" <c:if test="${row == map.recipe_list.type}">selected</c:if>>${row}
					</c:forEach>
				</select>
			<td>
				<select id="ingredient" name="ingredient" size="3" style="width: 150px; min-height: 50px;">
					<c:forEach var="row" items="${map.ingredient }">
					<option value="${row }" <c:if test="${row == map.recipe_list.ingredient}">selected</c:if>>${row}
					</c:forEach>
				</select>
			<td>
				<select id="time" name="time" size="3" style="width: 150px; min-height: 50px;">
					<c:forEach var="row" items="${map.time }">
					<option value="${row }" <c:if test="${row == map.recipe_list.time}">selected</c:if>>${row } (minute)
					</c:forEach> 	
				</select>
	</table>
	<div style="margin-bottom: 20px; margin-left: 50px;">
		<b>INGREDIENTS</b><br><br>
		<textarea id="ingredients" name="ingredients" rows="6" cols="72" style="margin-left: 10px;">${map.recipe_list.ingredients }</textarea>
	</div>
	<div style="margin-bottom: 20px; margin-left: 50px;">
		<b>COOKER</b><br><br>
		<textarea id="cooker" name="cooker" rows="6" cols="72" style="margin-left: 10px;">${map.recipe_list.cooker }</textarea>
	</div>
	
	<!-- ////////////////////////////////////////////////////////////////////////////////////////// -->
	<div style="text-align: center;">
		<input type="button" id="bntShowMore" name="btnShowMore" value="ShowMore" onclick="addForm(${map.step_list.size()});" style="width: 880px; height: 30px;">
	</div>
	<!-- ////////////////////////////////////////////////////////////////////////////////////////// -->
	<div id="addedFormDiv"></div><BR> <!-- 폼을 삽입할 DIV -->
	<div align="center">
		<input type="Button" value="ADD" onclick="addForm()">
		<input type="Button" value="REMOVE" onclick="delForm()">
		<input type="Submit" value="FINISH">
	</div>
	<br><br>
</form>
</body>
</html>